import tkinter as tk


def update_credits(event):
    selected_course_indices = course_listbox.curselection()
    if selected_course_indices:
        selected_course = course_listbox.get(selected_course_indices[0])

        credits = course_credits.get(selected_course, [])

        credit_listbox.delete(0, tk.END)

        for credit in credits:
            credit_listbox.insert(tk.END, credit)


def add_selection_to_textbox():

    selected_course_indices = course_listbox.curselection()
    selected_credit_indices = credit_listbox.curselection()

    if selected_course_indices and selected_credit_indices:
        selected_courses = [course_listbox.get(i) for i in selected_course_indices]
        selected_credits = [credit_listbox.get(i) for i in selected_credit_indices]

        for course in selected_courses:
            for credit in selected_credits:
                textbox.insert(tk.END, f"课程: {course}, 学分: {credit}\n")
    else:
        print("请确保在两个列表框中都选择了项。")


root = tk.Tk()
root.title("选课系统")

course_credits = {
    "数学": ["3", "4"],
    "物理": ["2", "3"],
    "化学": ["3", "5"],
    "生物": ["2", "4"]
}

course_listbox = tk.Listbox(root, selectmode=tk.SINGLE)  # 允许单选
for course in course_credits.keys():
    course_listbox.insert(tk.END, course)
course_listbox.grid(row=0, column=0)

credit_listbox = tk.Listbox(root, selectmode=tk.SINGLE)  # 允许单选
credit_listbox.grid(row=0, column=1)

textbox = tk.Text(root, height=10, width=40)
textbox.grid(row=1, column=0, columnspan=2)

add_button = tk.Button(root, text="添加选课", command=add_selection_to_textbox)
add_button.grid(row=2, column=0, columnspan=2)

course_listbox.bind('<<ListboxSelect>>', update_credits)

root.mainloop()